package com.learnyou.server.xingzuo.biz.helper;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.learnyou.server.xingzuo.common.config.SmsConfig;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * @author heweifeng
 * @Description:
 * @date 2022/12/3 16:03
 */
@Slf4j
public class SmsHelper {

    /**
     * 给指定手机号发送指定模板的短信
     * @param smsConfig  短信相关配置
     * @param phone 手机号
     * @param templateId 短信模板
     * @param params 短信模板参数
     * @return
     */
    public static boolean sendSms(SmsConfig smsConfig, String phone, String templateId, String[] params){

        //短信开关关闭则默认接口成功
        if(!Objects.equals(smsConfig.getEnable(), true)){
            return true;
        }
        Credential cred = new Credential(smsConfig.getSecretId(), smsConfig.getSecretKey());
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setReqMethod("POST");
        httpProfile.setConnTimeout(60);
        httpProfile.setEndpoint("sms.tencentcloudapi.com");
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        SmsClient client = new SmsClient(cred, "ap-nanjing",clientProfile);
        SendSmsRequest req = new SendSmsRequest();
        req.setSmsSdkAppId(smsConfig.getAppId());
        req.setSignName(smsConfig.getSignName());
        req.setTemplateId(templateId);
        req.setTemplateParamSet(params);
        req.setPhoneNumberSet(new String[]{"+86"+phone});
        try {
            SendSmsResponse res = client.SendSms(req);
            String resStr = SendSmsResponse.toJsonString(res);
            log.info(resStr);
            Object resCode = JSONUtil.getByPath(JSONUtil.parseObj(resStr), "SendStatusSet[0].Code");
            log.info(StrUtil.str(resCode, CharsetUtil.CHARSET_UTF_8));
            if (!Objects.equals(resCode, "Ok")){
                return false;
            }
        } catch (TencentCloudSDKException e) {
            log.error("sms send error", e);
            return false;
        }
        return true;
    }
}
